<?php

namespace App\Services\MakeBoxProductOrder;

use App\Models\Order;
use App\Models\Address;
use App\Models\BlindBoxOrder;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class takeBoxProductOrderRequest extends FormRequest
{
	protected ?Address $address = null;

	public function rules(): array
	{

		$addressId =  (int)request('address_id');
		if ($addressId) {
			$this->address = Address::find($addressId);
		}

		$orderId =  (int)request('blind_box_order_id');
		if ($orderId) {
			$this->order = BlindBoxOrder::find($orderId);
		}

		return [
			'blind_box_order_id' => ['required', $this->blindBoxOrder()],
			'address_id' => ['required', $this->address()],
		];
	}

	public function address()
	{
		return function ($attribute, $value, $fail) {
			if (!$this->address) {
				return $fail('地址不存在');
			} elseif (!Order::isAddressSupported($this->address)) {
				return $fail('地址不在配送范围');
			}
			return true;
		};
	}

	public function blindBoxOrder()
	{

		return function ($attribute, $value, $fail) {
			if (!$box = BlindBoxOrder::find($value)) {
				return $fail('订单不存在');
			}elseif(! $box->paid_at){
				return $fail('订单未支付');
			}elseif($box->is_taken){
				return $fail('订单已被领取');
			}
			return true;
		};
	}

	public function getAddress(): Address
	{
		return $this->address;
	}
	

	public function getBlindBoxOrder()
	{
		return $this->order;
	}

	
}
